package ez

import (
	"encoding/json"
	"strings"
)

func CreateMapString() map[string]interface{} {
	return map[string]interface{}{}
}
func CreateMapInt() map[int]interface{} {
	return map[int]interface{}{}
}

type IntKeyMap map[int]interface{}

func (s IntKeyMap) Len() int           { return len(s) }
func (s IntKeyMap) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s IntKeyMap) Less(i, j int) bool { return i < j }

type StringKeyMap map[string]interface{}

func (s StringKeyMap) Len() int              { return len(s) }
func (s StringKeyMap) Swap(i, j string)      { s[i], s[j] = s[j], s[i] }
func (s StringKeyMap) Less(i, j string) bool { return i < j }

type M map[string]interface{}

func (s M) Len() int              { return len(s) }
func (s M) Swap(i, j string)      { s[i], s[j] = s[j], s[i] }
func (s M) Less(i, j string) bool { return i < j }
func (s *M) String() string       { data, _ := json.Marshal(s); return string(data) }

func Mapper(src interface{}, key string, v interface{}) interface{} {
	str, e := json.Marshal(src)
	if PrintError(e) {
		return src
	}
	fields := strings.Split(key, ".")
	mapper := make(map[string]interface{})
	e = json.Unmarshal(str, &mapper)
	if PrintError(e) {
		return src
	}
	if len(fields) == 1 {
		mapper[key] = v
		return mapper
	}
	value, ok := mapper[fields[0]]
	if !ok {
		value = make(map[string]interface{})
	}
	newKey := strings.Join(fields[1:], ".")
	mapper[fields[0]] = Mapper(value, newKey, v)
	return mapper
}

func DbCreateFilter() map[string]interface{} {
	return make(map[string]interface{})
}
